/**
 * Created by 小润 on 2017/5/22.
 * Insert by yl on 2017/5/22.
 */
$(document).ready(function(){
    
    $('#paymethod').hide()
    $('.go-back').click(function(){

        $('#paymethod').hide()
        $('.shows').show();
        
        

    });

//  微信支付

    $(".btn-success").on("click",function(){

        var donationId = $(this).siblings(".devoteId").val();
        var userId = localStorage.getItem("userId")
        var data = {
            "userId": userId,
            "donationId": donationId
        }
        $.ajax({
            type: "get",
            url: '/api/v1/orderPay/wxPayinsertOrder',
            data: data,
            success: function (data) {
                console.log(data);
                donationid = data.data.donationId;
                openId = data.data.openId;
                orderpayid = data.data.id;
            },
            error: function (msg) {
                alert('请求失败');
                console.log(msg)

            }
        });
        var userId = localStorage.getItem("userId")
        var data ={
            "userId": userId
        }
        $('.shows').hide();
        $('#paymethod').show();
        $("#devo").focus()
    })

    $("#pay").on("click",function(){
        var moneyNum = $("#devo").val();
       // var donationId =$("#donationid").val();
        var userId = localStorage.getItem("userId")
        var data = {
            "userId": userId,
            "openId":openId,
            "donationId":donationid,
            "orderpayid":orderpayid,
            "moneyNum":moneyNum
        }
        if(moneyNum.trim() == ""|| parseFloat(oPay.value)<=0.0){
            alert("捐赠有误")
        }else{
            $.ajax({
                type: "post",
                url: '/api/v1/orderPay/wxPayUnifiedOrder',
                data: data,
                success: function (data) {
                    console.log("统一下单完成");
                    var oderParams = data.data;
                    console.log(oderParams);
                    toPay(oderParams);
                },
                error: function (msg) {
                    alert('请求失败');
                    console.log(msg)

                }
            });
        }
    })


    $(".show-detail").on("click",function () {
        var orderId=$(this).children(".orderId").val();
        window.location.href="/h5/user/devoteDetail?id="+orderId;
    })
    function onBridgeReady(oderParams) {
        var payParams = {
            "appId":oderParams.appId,
            "timeStamp":oderParams.timeStamp, //时间戳，自1970年以来的秒数
            "nonceStr":oderParams.nonceStr, //随机串
            "package": oderParams.package,
            "signType":oderParams.signType, //微信签名方式：
            "paySign":oderParams.paySign //微信签名
        }
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest',payParams,
            function(res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    // window.location.href = "/api/v1/orderPay/wxPayResultNotify";
                    var data = {
                        "orderpayid":data.data.orderpayid
                    }
                    $.ajax({
                        type: "post",
                        url: '/api/v1/orderPay/wxPayResult',
                        data: data,
                        success: function (data) {
                           // window.location.reload();
                            window.location.href = "/h5/user/devote";
                        },
                        error: function (msg) {
                            alert('有延迟，请求失败');
                            console.log(msg)
                            window.location.href = "/h5/user/devote";

                        }
                    });
                    window.location.href = "/h5/user/devote";
                } // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回 ok，但并不保证它绝对可靠。
                else {
                    console.log(res.err_msg);
                    //
                    //支付失败后的操作
                    //打开页面有问题，这个是请求的接口，POST方式，href是浏览器打开方式为get，会出现提示的get方式问题，
                    //主要问题的逻辑应该是打开一个页面，而不是请接口
                    window.location.href = "/h5/user/devote";
                }
            }
        );
    }
    function toPay(oderParams) {
        if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
        } else {
            onBridgeReady(oderParams);
        }
    }
});
var oPay = document.getElementById("devo");
oPay.oninput = function() {
    clearNoNum(this)
}
function clearNoNum(obj){

    obj.value = obj.value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/^.{1}$/g,"0");//第一位不能为.
    obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的

    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
    if(obj.value.indexOf(".")< 0 && obj.value !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        obj.value= parseFloat(obj.value);
    }
}
